package com.zeny.coding.util;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.vod.model.v20170321.DeleteVideoRequest;
import com.zeny.coding.config.OssConfig;
import com.zeny.coding.config.VodConfig;
import com.zeny.coding.dto.FileDto;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

/**
 * <h2>删除阿里云文件</h2>
 *
 * @Author Zeny
 */
@Slf4j
@Component
public class DeleteFileUtil {

    @Autowired
    private OssConfig ossConfig;

    @Autowired
    private VodConfig vodConfig;

    /**
     * <h2>删除阿里云文件</h2>
     * @param fileDto
     **/
    public void delete(FileDto fileDto) {
        String vod = fileDto.getVod();
        if (StringUtils.isEmpty(vod)) {
            deleteOss(fileDto);
        } else {
            deleteVod(fileDto.getVod());
        }
    }
    /**
     * <h2>删除oss文件</h2>
     * @param fileDto
     **/
    private void deleteOss(FileDto fileDto) {
        OSS ossClient = new OSSClientBuilder()
                .build(ossConfig.getEndpoint(),
                        ossConfig.getAccessKeyId(),
                        ossConfig.getAccessKeySecret());
        ossClient.deleteObject(ossConfig.getBucket(), fileDto.getPath());
        ossClient.shutdown();
    }

    /**
     * <h2>删除多个vod视频</h2>
     * @param videoIds
     **/
    private void deleteVod(String videoIds) {
        DefaultAcsClient vodClient = null;
        try {
            vodClient = VodUtil.initVodClient(vodConfig.getAccessKeyId(), vodConfig.getAccessKeySecret());
            DeleteVideoRequest request = new DeleteVideoRequest();
            request.setVideoIds(videoIds);
            vodClient.getAcsResponse(request);
        }catch (Exception e) {
            log.error("vod视频删除异常: {}", e.fillInStackTrace());
        } finally {
            vodClient.shutdown();
        }

    }
}
